package com.cinema.servlet.admin;

import com.cinema.dao.*;
import com.cinema.entity.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 管理员场次管理Servlet
 */
public class AdminShowtimeServlet extends HttpServlet {
    private ShowtimeDAO showtimeDAO = new ShowtimeDAO();
    private MovieDAO movieDAO = new MovieDAO();
    private CinemaDAO cinemaDAO = new CinemaDAO();
    private HallDAO hallDAO = new HallDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        if ("add".equals(action)) {
            showAddShowtimeForm(request, response);
        } else if ("edit".equals(action)) {
            showEditShowtimeForm(request, response);
        } else if ("delete".equals(action)) {
            handleDeleteShowtime(request, response);
        } else {
            showShowtimeList(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        if ("add".equals(action)) {
            handleAddShowtime(request, response);
        } else if ("edit".equals(action)) {
            handleEditShowtime(request, response);
        } else {
            doGet(request, response);
        }
    }

    /**
     * 显示场次列表
     */
    private void showShowtimeList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            String movieIdStr = request.getParameter("movieId");
            List<Showtime> showtimes;
            Movie selectedMovie = null;

            // 如果指定了电影ID，只显示该电影的场次
            if (movieIdStr != null && !movieIdStr.trim().isEmpty()) {
                try {
                    Integer movieId = Integer.parseInt(movieIdStr);
                    showtimes = showtimeDAO.findByMovieId(movieId);
                    selectedMovie = movieDAO.findById(movieId);
                    request.setAttribute("selectedMovie", selectedMovie);
                } catch (NumberFormatException e) {
                    showtimes = showtimeDAO.findAll();
                }
            } else {
                showtimes = showtimeDAO.findAll();
            }

            request.setAttribute("showtimes", showtimes);

            // 检查是否有消息
            String message = request.getParameter("message");
            if (message != null && !message.trim().isEmpty()) {
                request.setAttribute("message", message);
            }

            request.getRequestDispatcher("/admin/showtimes.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取场次列表失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }

    /**
     * 显示添加场次表单
     */
    private void showAddShowtimeForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            // 获取电影、影院、影厅列表
            List<Movie> movies = movieDAO.findNowShowing();
            List<Cinema> cinemas = cinemaDAO.findAll();
            List<Hall> halls = hallDAO.findAll();

            request.setAttribute("movies", movies);
            request.setAttribute("cinemas", cinemas);
            request.setAttribute("halls", halls);
            request.setAttribute("action", "add");

            request.getRequestDispatcher("/admin/showtime-form.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "加载表单数据失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }

    /**
     * 显示编辑场次表单
     */
    private void showEditShowtimeForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String idStr = request.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin/showtimes");
            return;
        }

        try {
            Integer id = Integer.parseInt(idStr);
            Showtime showtime = showtimeDAO.findById(id);

            if (showtime == null) {
                request.setAttribute("error", "场次不存在");
                request.getRequestDispatcher("/error/404.jsp").forward(request, response);
                return;
            }

            // 获取电影、影院、影厅列表
            List<Movie> movies = movieDAO.findNowShowing();
            List<Cinema> cinemas = cinemaDAO.findAll();
            List<Hall> halls = hallDAO.findAll();

            request.setAttribute("showtime", showtime);
            request.setAttribute("movies", movies);
            request.setAttribute("cinemas", cinemas);
            request.setAttribute("halls", halls);
            request.setAttribute("action", "edit");

            request.getRequestDispatcher("/admin/showtime-form.jsp").forward(request, response);

        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/admin/showtimes");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取场次信息失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }

    /**
     * 处理添加场次
     */
    private void handleAddShowtime(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            Showtime showtime = createShowtimeFromRequest(request);

            boolean success = showtimeDAO.addShowtime(showtime);

            if (success) {
                String message = URLEncoder.encode("场次添加成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/admin/showtimes?message=" + message);
            } else {
                request.setAttribute("error", "添加场次失败");
                showAddShowtimeForm(request, response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "添加场次过程中发生错误：" + e.getMessage());
            showAddShowtimeForm(request, response);
        }
    }

    /**
     * 处理编辑场次
     */
    private void handleEditShowtime(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            Showtime showtime = createShowtimeFromRequest(request);
            String idStr = request.getParameter("id");
            showtime.setId(Integer.parseInt(idStr));

            boolean success = showtimeDAO.updateShowtime(showtime);

            if (success) {
                String message = URLEncoder.encode("场次更新成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/admin/showtimes?message=" + message);
            } else {
                request.setAttribute("error", "更新场次失败");
                showEditShowtimeForm(request, response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "更新场次过程中发生错误：" + e.getMessage());
            showEditShowtimeForm(request, response);
        }
    }

    /**
     * 处理删除场次
     */
    private void handleDeleteShowtime(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String idStr = request.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin/showtimes");
            return;
        }

        try {
            Integer id = Integer.parseInt(idStr);
            boolean success = showtimeDAO.deleteShowtime(id);

            if (success) {
                String message = URLEncoder.encode("场次删除成功", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/admin/showtimes?message=" + message);
            } else {
                String error = URLEncoder.encode("删除场次失败", "UTF-8");
                response.sendRedirect(request.getContextPath() + "/admin/showtimes?error=" + error);
            }

        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/admin/showtimes");
        } catch (Exception e) {
            e.printStackTrace();
            String error = URLEncoder.encode("删除场次过程中发生错误", "UTF-8");
            response.sendRedirect(request.getContextPath() + "/admin/showtimes?error=" + error);
        }
    }

    /**
     * 从请求中创建场次对象
     */
    private Showtime createShowtimeFromRequest(HttpServletRequest request) throws ParseException {
        Showtime showtime = new Showtime();

        // 基本信息
        showtime.setMovieId(Integer.parseInt(request.getParameter("movieId")));
        showtime.setCinemaId(Integer.parseInt(request.getParameter("cinemaId")));
        showtime.setHallId(Integer.parseInt(request.getParameter("hallId")));
        showtime.setPrice(new BigDecimal(request.getParameter("price")));
        showtime.setStatus(request.getParameter("status"));

        // 日期时间处理
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat html5DatetimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");

        showtime.setShowDate(dateFormat.parse(request.getParameter("showDate")));
        showtime.setShowTime(timeFormat.parse(request.getParameter("showTime")));

        // 预售开始时间和订票截止时间
        String presaleStartStr = request.getParameter("presaleStart");
        if (presaleStartStr != null && !presaleStartStr.trim().isEmpty()) {
            try {
                // 首先尝试HTML5 datetime-local格式 (yyyy-MM-ddTHH:mm)
                showtime.setPresaleStart(html5DatetimeFormat.parse(presaleStartStr));
            } catch (ParseException e) {
                try {
                    // 如果失败，尝试标准格式 (yyyy-MM-dd HH:mm)
                    showtime.setPresaleStart(datetimeFormat.parse(presaleStartStr));
                } catch (ParseException e2) {
                    System.err.println("无法解析预售开始时间: " + presaleStartStr);
                    throw new ParseException("预售开始时间格式错误: " + presaleStartStr, 0);
                }
            }
        }

        String bookingEndStr = request.getParameter("bookingEnd");
        if (bookingEndStr != null && !bookingEndStr.trim().isEmpty()) {
            try {
                // 首先尝试HTML5 datetime-local格式 (yyyy-MM-ddTHH:mm)
                showtime.setBookingEnd(html5DatetimeFormat.parse(bookingEndStr));
            } catch (ParseException e) {
                try {
                    // 如果失败，尝试标准格式 (yyyy-MM-dd HH:mm)
                    showtime.setBookingEnd(datetimeFormat.parse(bookingEndStr));
                } catch (ParseException e2) {
                    System.err.println("无法解析订票截止时间: " + bookingEndStr);
                    throw new ParseException("订票截止时间格式错误: " + bookingEndStr, 0);
                }
            }
        }

        // 获取影厅总座位数
        Hall hall = hallDAO.findById(showtime.getHallId());
        if (hall != null) {
            showtime.setTotalSeats(hall.getTotalSeats());
            showtime.setAvailableSeats(hall.getTotalSeats());
        }

        return showtime;
    }
}
